package com.myspace.backend.service.impl.post;

import com.myspace.backend.mapper.PostMapper;
import com.myspace.backend.pojo.Post;
import com.myspace.backend.pojo.User;
import com.myspace.backend.service.impl.utils.UserDetailsImpl;
import com.myspace.backend.service.post.PostAddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class PostAddServiceImpl implements PostAddService {

    @Autowired
    private PostMapper postMapper;

    @Override
    public Map<String, String> postAdd(String content) {
        Map<String, String> map = new HashMap<>();

        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();

        int user_id = user.getId();
        Post post = new Post(null, user_id, content);
        postMapper.insert(post);

        map.put("error_message", "success");

        return map;
    }
}
